package progress.exa28_1.part6;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 *
 * 学习使用显式锁ReentrantLock来进行同步编程
 */
public class LockStudy {

    private static Account account = new Account();

    public static void main(String[] args) {
        //创建线程池
        ExecutorService executor= Executors.newCachedThreadPool();
        //循环添加任务
        for(int i=0;i<1000;i++) {
            executor.execute(new AddAPennyTask());
        }
        // 关闭线程池
        executor.shutdown();

        //所有任务都执行完
        while(true) {
            if(executor.isTerminated()){
                System.out.println("任务执行完毕！！");
                break;
            }
        }

        System.out.println("what is balance? "+account.getBalance());
    }

    public static class AddAPennyTask implements Runnable{
        public void run() {
            account.deposit(1);
        }

    }

    private static class Account {

        //创建一个互斥锁
        private static final Lock lock = new ReentrantLock();

        private int balance = 0;

        public int getBalance(){
            return balance;
        }

        public void deposit(int amount) {
            //获取一个锁
            lock.lock();
            try{
                int newBalance = balance+amount;
                Thread.sleep(5);
                balance = newBalance;
            }
            catch(InterruptedException ex) {
                System.out.println("线程中断！！");
            }
            finally{
                //释放锁
                lock.unlock();
            }
        }

    }

}
